import React, { Component } from "react";
import { Table, Input, Button, Popconfirm, Form ,Divider,Select, Upload,  Icon, DatePicker, Modal} from 'antd';
import moment from "moment";
import Content from "../../components/Content/Content";
import Search from "antd/lib/input/Search";

const { Item } = Form;

function makeFormData(obj, form_data) {
  var data = [];
  if (obj instanceof File){
      data.push({key: "", value: obj});
  }else if (obj instanceof Array ){
      for (var j=0,len=obj.length;j<len;j++){
          var arr = makeFormData(obj[j]);
          for (var k=0,l=arr.length;k<l;k++){
              var key = !!form_data ? j+arr[k].key : "["+j+"]"+arr[k].key;
              data.push({key: key, value: arr[k].value})
          }
      }
  }else if (typeof obj == 'object'){
      for (var j in obj){
          var arr = makeFormData(obj[j]);
          for (var k=0,l=arr.length;k<l;k++){
              var key = !!form_data ? j+arr[k].key : "."+j+""+arr[k].key;
              data.push({key: key, value: arr[k].value})
          }
      }
  }else{
      data.push({key: "", value: obj});
  }
  if (!!form_data){
      // 封装
      for (var i=0,len=data.length;i<len;i++){
          form_data.append(data[i].key, data[i].value)
      }
  }else{
      return data;
  }
};

const props = {
  action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  listType: 'picture',
  // defaultFileList: [...fileList],
};

const dateFormat = "YYYY-MM-DD HH:mm:ss";

const EditableContext = React.createContext();
const { Option } = Select;
const InputGroup = Input.Group;
const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} 不能为空.`,
              
            },
          ],
          initialValue: record[dataIndex],
        })(<Input className='InputValue' ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"

        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '序号',
        dataIndex: 'id',
        fixed: 'left',
        width:200,
        editable: false,
      },
      {
        title: '新增分离菌株编号',
        dataIndex: 'add_separate_num',
        fixed: 'left',
        width:200,
        editable: true,
      },
      {
        title: '采集样品编号',
        dataIndex: 'Acq_id',
        editable: true,
      },
      {
        title: '采集样品预处理方法',
        dataIndex: 'add_method',
        editable: true,
      },
      {
        title: '菌种类别',
        width: 200,
        dataIndex: 'add_jzlb',
        render: (text, record) => (
          <Select defaultValue={text} style={{width: '100%'}}>
            <Option value="fxj">放线菌</Option>
            <Option value="xj">细菌</Option>
            <Option value="xxzj">真菌（小型真菌）</Option>
            <Option value="jmzj">真菌（酵母）</Option>
            <Option value="dxzj">真菌（大型真菌）</Option>
            <Option value="qt">其他类型</Option>
          </Select>
              )
      },
      {
        title: '属名',
        dataIndex: 'add_sm',  
        editable: true,     
      },
      {
        title: '近缘菌株',
        dataIndex: 'add_jyjz',
        editable: true,
      },
      {
        title: '近缘菌株相似性(%)',
        dataIndex: 'add_flid',
        editable: true,
      },
      {
        title: '菌株图片',
        dataIndex: 'add_pic',
      },
      {
        title: '菌株序列',
        dataIndex: 'info_jyxl',
        editable: true,
        
      },
      {
        title: 'Blast文件',
        dataIndex: 'info_blastwj',
      },
      {
        title: '基因序列原始文件',
        dataIndex: 'info_jyxlwj',
      },

      /**
      {
        title: '放线菌',
        dataIndex: 'add_fxj',
        render: (text, record) => (
          <Select defaultValue={text} style={{width: '100%'}}>
            <Option value="passage">PA</Option>
            <Option value="methane">PB</Option>
            <Option value="zhenjun">拼接序列</Option>

          </Select>
         )
      },
      {
        title: '细菌',
        dataIndex: 'add_xj',
        render: (text, record) => (
          <Select defaultValue={text} style={{width: '100%'}}>
            <Option value="passage">PA</Option>
            <Option value="methane">PB</Option>
            <Option value="zhenjun">拼接序列</Option>

          </Select>
        )
      },
      {
        title: '真菌',
        dataIndex: 'add_zj',
        render: (text, record) => (
          <Select defaultValue={text} style={{width: '100%'}}>
            <Option value="else">ITS</Option>
            <Option value="passage">TEF1</Option>
            <Option value="methane">EF1</Option>
            <Option value="zhenjun">RPB2</Option>
            <Option value="jioamu">RPB1</Option>
            <Option value="big">TUB2</Option>
            <Option value="else">LSU</Option>
          </Select>
         )
      },
      {
        title: '其他',
        dataIndex: 'add_qtjzlx',
        editable: true
      },
      **/

      {
        title: '其他文件上传',
        dataIndex: 'add_qtjzwjsc',
      },
      {
        title: '分离培养基',
        dataIndex: 'add_flpyjid',
        editable: true,
      },
      {
        title: '传代培养基',
        dataIndex: 'add_cdpyjid',
        editable: true,
      },
      {
        title: '分离人',
        dataIndex: 'add_person',
        editable: true,
      },
      {
        title: '分离时间',
        dataIndex: 'add_time',
        editable: true
      },
      {
        title: '工作人员',
        dataIndex: 'worker',
        editable: true
      },
      {
        title: '操作',
        dataIndex: 'operation_xz',
        fixed: 'right',
        width:100,
        render: (text, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.id)}>
              <a>删除</a>
            </Popconfirm>
            
          ) : null,
      },
    ];
 
  }

  selectFile = (env, prefix, idx) => {
    let files = env.target.files;
    let filename = files[0].name;
    // document.getElementById(prefix + idx).value = filename;
  }

  state = {
    dataSource: [], 

    newData: {},
    showAddModal: false,

    count: 0,
    loading: false,
    pageNum: 1,
    pageSize: 100
  };

  onShowSizeChange = (current, pageSize) => {
    this.loadData(this.state.acqType, current, pageSize);
    this.setState({
        pageSize: pageSize
    })
  }

  paginationProps = {
    showSizeChanger: true,//设置每页显示数据条数
    showQuickJumper: false,
    showTotal: () => `共${this.state.count}条`,
    pageSize: this.state.pageSize,
    total: this.state.count,  //数据的总的条数
    onChange: (current) => this.loadData(current), //点击当前页码
    onShowSizeChange: (current, pageSize) => {//设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
        console.log(pageSize);
        this.onShowSizeChange(current, pageSize)
    }
  }  

  onSelectChange = selectedRowKeys => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
  
  handleDelete = id => {
    const dataSource = [...this.state.dataSource];
    // 如果是新数据尚未保存，那么可以直接删除
    if( this.state.newData.id != null ) {
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      return;
    }
    
    const url = global.api.strainAdd + id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    }) 

  };

  loadData = (current = 1) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    const url = global.api.strainInfo + '?_t=' + (new Date()).valueOf();
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count})
    })
    .catch(err => {
      Modal.error({
        content: '网络异常!',
      });
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  handleSave = (row, showAlert) => {

    this.setState({
      loading: true
    })
    
    if( this.state.newData.id ) {

      this.state.newData.add_pic = document.getElementById('add_pic').files[0];
      this.state.newData.info_blastwj = document.getElementById('info_blastwj').files[0];
      this.state.newData.info_jyxlwj = document.getElementById('info_jyxlwj').files[0];
      this.state.newData.add_qtjzwjsc = document.getElementById('add_qtjzwjsc').files[0];
   
      var formDatas = new FormData();
      makeFormData(this.state.newData, formDatas); // 调用此方法
  
      const url = global.api.strainAdd;
      return global.network.post(url, formDatas)
      .then(res => {  
        
        this.loadData(1);
  
        Modal.success({
          content: '保存成功!',
        });
        this.setState({
          loading: false
        })
      })
      .catch(err => {
        Modal.error({
          content: '保存出错，请检查传入的参数是否已经填写！',
        });
        this.setState({
          loading: false
        })
      }) 
  
    } else {

      const url = global.api.strainAdd + row.id + '/';
      return global.updatedata.put(url, row)
      .then(res => {  
        
        this.loadData(1);
  
        Modal.success({
          content: '保存成功!',
        });
        this.setState({
          loading: false
        })
      })
      .catch(err => {
        Modal.error({
          content: '保存出错，请检查传入的参数是否已经填写！',
        });
        this.setState({
          loading: false
        })
      }) 
  
    }
    
  };

  selectFile = (evt, idx) => {
    let files = evt.target.files;
    let filename = files[0].name;
    document.getElementById(idx).value = filename;
  }

  render() {
    const { dataSource } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 }
      }
    };    
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Content>
        <Button onClick={() => this.setState({showAddModal: true})} type="primary" style={{ marginLeft:'24px' }}>
          添加
        </Button>
        
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          pagination={this.paginationProps}
          columns={columns}
          scroll={{ x: 3000,y:400}}
        />

        <Modal
          title="Basic Modal"
          visible={this.state.showAddModal}
          onOk={() => this.setState({showAddModal: false})}
          onCancel={() => this.setState({showAddModal: false})}
        >
          <Form {...formItemLayout} onSubmit={this.onSubmit} colon={false}>

            <div style={{display:'flex'}}>
              <span style={{flex:'1'}}>
                  <Item label="任务编号">
                      <Input defaultValue={this.state.newData.id } onChange={e => this.state.newData.id = e.target.value} />
                  </Item>
                  <Item label="新增分离菌株编号">
                      <Input defaultValue={this.state.newData.add_separate_num } onChange={e => this.state.newData.add_separate_num = e.target.value} />
                  </Item>
                  <Item label="采集样品编号">
                      <Input defaultValue={this.state.newData.Acq_id } onChange={e => this.state.newData.Acq_id = e.target.value} />
                  </Item>
                  <Item label="采集样品预处理方法">
                      <Input defaultValue={this.state.newData.add_method } onChange={e => this.state.newData.add_method = e.target.value} />
                  </Item>
                  <Item label="菌种类别">
                    <Select
                      defaultValue={this.state.newData.add_jzlb }
                      onChange={value => this.state.newData.add_jzlb  = value}
                      style={{ width: "100%" }}
                      tokenSeparators={[","]}
                      showArrow={true}
                    >
                      <Option value="fxj">放线菌</Option>
                      <Option value="xj">细菌</Option>
                      <Option value="xxzj">真菌（小型真菌）</Option>
                      <Option value="jmzj">真菌（酵母）</Option>
                      <Option value="dxzj">真菌（大型真菌）</Option>
                      <Option value="qt">其他类型</Option>
                    </Select>
                  </Item>
                  <Item label="属名">
                      <Input defaultValue={this.state.newData.add_sm } onChange={e => this.state.newData.add_sm = e.target.value} />
                  </Item>
                  <Item label="近缘菌株">
                      <Input defaultValue={this.state.newData.add_jyjz } onChange={e => this.state.newData.add_jyjz = e.target.value} />
                  </Item>
                  <Item label="与近缘菌株最高相似性(%)">
                      <Input defaultValue={this.state.newData.add_flid } onChange={e => this.state.newData.add_flid = e.target.value} />
                  </Item>

                </span>
                <span style={{flex:'1'}}>  
                <Item label="菌株图片">
                    <Input id="add_pic" type="file" style={{display: 'none'}} onChange={env => this.selectFile(env, 'add_pic_s')}  />
                    <Search
                      placeholder=""
                      id="add_pic_s"
                      enterButton="上传"
                      onSearch={value => document.getElementById("add_pic").click()}
                    />   
                  </Item>
                  <Item label="菌株序列">
                      <Input defaultValue={this.state.newData.info_jyxl } onChange={e => this.state.newData.info_jyxl = e.target.value} />
                  </Item>
                  <Item label="Blast文件">
                    <Input id="info_blastwj" type="file" style={{display: 'none'}} onChange={env => this.selectFile(env, 'info_blastwj_s')}  />
                    <Search
                      id="info_blastwj_s"
                      placeholder=""
                      enterButton="上传"
                      onSearch={value => document.getElementById("info_blastwj").click()}
                    />                      
                  </Item>
                  <Item label="基因序列原始文件">   
                    <Input id="info_jyxlwj" type="file" style={{display: 'none'}} onChange={env => this.selectFile(env, 'info_jyxlwj_s')}  />
                    <Search
                      id="info_jyxlwj_s"
                      placeholder=""
                      enterButton="上传"
                      onSearch={value => document.getElementById("info_jyxlwj").click()}
                    />                     
                  </Item>                
                  <Item label="其他文件上传">   
                    <Input id="add_qtjzwjsc" type="file" style={{display: 'none'}} onChange={env => this.selectFile(env, 'add_qtjzwjsc_s')}  />
                    <Search
                      id="add_qtjzwjsc_s"
                      placeholder=""
                      enterButton="上传"
                      onSearch={value => document.getElementById("add_qtjzwjsc").click()}
                    />                          
                  </Item>                                   
                  <Item label="分离培养基">
                      <Input defaultValue={this.state.newData.add_flpyjid } onChange={e => this.state.newData.add_flpyjid = e.target.value} />
                  </Item>                                    
                  <Item label="传代培养基">
                      <Input defaultValue={this.state.newData.add_cdpyjid } onChange={e => this.state.newData.add_cdpyjid = e.target.value} />
                  </Item>                                    
                  <Item label="分离人">
                      <Input defaultValue={this.state.newData.add_person } onChange={e => this.state.newData.add_person = e.target.value} />
                  </Item>                                 
                  <Item label="工作人员">
                      <Input defaultValue={this.state.newData.worker } onChange={e => this.state.newData.worker = e.target.value} />
                  </Item>
                  <Item label="分离时间" wrapperCol>
                    <DatePicker
                      style={{ width: "100%" }}
                      // defaultValue={moment(this.state.newData.add_time)  }
                      onChange={(date, dateStr) => this.state.newData.add_time  = dateStr}
                      format={dateFormat}
                      dateRender={current => {
                        const style = {};
                        if (current.date() === 1) {
                          style.border = "1px solid #1890ff";
                          style.borderRadius = "50%";
                        }
                        return (
                          <div className="ant-calendar-date" style={style}>
                            {current.date()}
                          </div>
                        );
                      }}
                    />
                  </Item>

                  <Button type="primary" onClick={this.handleSave} style={{marginLeft:'100px', marginTop: '30px'}}>保存</Button>

              </span>
            </div>

          </Form>
        </Modal>

      </Content>
    );
  }
}

const ActivityScreeningPrimary = Form.create()(EditableTable);
export default ActivityScreeningPrimary;
